import { defineStore } from 'pinia';
import { login, getUserInfo, logout } from '@/api/user';
import type { UserInfo, LoginParams } from '@/api/user';
import router from '@/router';

interface UserState {
  token: string;
  userInfo: UserInfo | null;
  roles: string[];
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    token: localStorage.getItem('token') || '',
    userInfo: null,
    roles: [],
  }),
  getters: {
    getToken(): string {
      return this.token;
    },
    getUserInfo(): UserInfo | null {
      return this.userInfo;
    },
    getRoles(): string[] {
      return this.roles;
    },
    isLogin(): boolean {
      return !!this.token;
    },
  },
  actions: {
    // 设置Token
    setToken(token: string) {
      this.token = token;
      localStorage.setItem('token', token);
    },
    // 设置用户信息
    setUserInfo(userInfo: UserInfo) {
      this.userInfo = userInfo;
      this.roles = userInfo.roles || [];
    },
    // 清除用户信息
    resetInfo() {
      this.token = '';
      this.userInfo = null;
      this.roles = [];
      localStorage.removeItem('token');
    },
    // 登录
    async login(loginParams: LoginParams) {
      try {
        const res = await login(loginParams);
        this.setToken(res.token);
        return true;
      } catch (error) {
        return false;
      }
    },
    // 获取用户信息
    async getInfo() {
      try {
        const userInfo = await getUserInfo();
        this.setUserInfo(userInfo);
        return userInfo;
      } catch (error) {
        return null;
      }
    },
    // 登出
    async logout() {
      try {
        await logout();
      } catch (error) {
        console.error('登出失败', error);
      } finally {
        this.resetInfo();
        router.push('/login');
      }
    },
  },
}); 